import 'package:flutter_datetime_picker_plus/flutter_datetime_picker_plus.dart';
import 'package:intl/intl.dart';

class MouthDayWeekPicker extends CommonPickerModel {
  final List<DateTime> dates;

  MouthDayWeekPicker({
    required DateTime minTime,
    required DateTime maxTime,
    DateTime? currentTime,
    LocaleType? locale,
  }) : dates = _generateDates(minTime, maxTime),
       super(locale: locale) {
    this.currentTime = currentTime ?? DateTime.now();

    int index = dates.indexWhere(
      (d) =>
          d.year == this.currentTime.year &&
          d.month == this.currentTime.month &&
          d.day == this.currentTime.day,
    );
    if (index < 0) index = 0;

    super.setLeftIndex(index);
    super.setMiddleIndex(0);
    super.setRightIndex(0);
  }

  static List<DateTime> _generateDates(DateTime min, DateTime max) {
    final List<DateTime> list = [];
    DateTime tmp = min;
    while (!tmp.isAfter(max)) {
      list.add(tmp);
      tmp = tmp.add(const Duration(days: 1));
    }
    return list;
  }

  String _format(DateTime d) {
    final weekDays = ['一', '二', '三', '四', '五', '六', '日'];
    return DateFormat('M月d日').format(d) + '  星期${weekDays[d.weekday - 1]}';
  }

  @override
  String? leftStringAtIndex(int index) {
    if (index >= 0 && index < dates.length) return _format(dates[index]);
    return null;
  }

  @override
  String? middleStringAtIndex(int index) => ' ';
  @override
  String? rightStringAtIndex(int index) => ' ';

  @override
  String leftDivider() => '';
  @override
  String rightDivider() => '';
  @override
  List<int> layoutProportions() => [1, 0, 0];

  @override
  DateTime finalTime() {
    final index = currentLeftIndex();
    if (index >= 0 && index < dates.length) return dates[index];
    return dates.first;
  }
}
